package com.wtwd.campus.vcom.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.entity.*;
import com.wtwd.campus.hxy.service.CommandRecordService;
import com.wtwd.campus.service.CustomerDealCmdService;
import com.wtwd.campus.service.LocationService;
import com.wtwd.campus.service.PolygonFenceService;
import com.wtwd.campus.service.RedisService;
import com.wtwd.campus.utils.HttpclientUtil;
import com.wtwd.campus.utils.RegionUtil;
import com.wtwd.campus.vcom.entity.VcomData;
import com.wtwd.campus.vcom.common.Constant;
import com.wtwd.campus.vcom.entity.GetPhoneDatasEntity;
import com.wtwd.campus.vcom.entity.VcomPhone;
import com.wtwd.campus.vcom.entity.VcomWarningRecord;
import com.wtwd.campus.vcom.service.VcomFenceService;
import com.wtwd.campus.vcom.service.VcomH5Service;
import com.wtwd.campus.vcom.service.VcomPhoneService;
import com.wtwd.campus.vcom.service.VcomService;
import com.wtwd.campus.vcom.utils.VcomPushUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author mjy
 * @date 2022/11/07
 * @description
 */
@Service
public class VcomServiceImpl implements VcomService {

    private static final Logger logger = LoggerFactory.getLogger(VcomServiceImpl.class);

    @Resource
    private CommandRecordService commandRecordService;

    @Resource
    private RedisService redisService;

    @Resource
    private VcomPhoneService vcomPhoneService;

    @Resource
    private LocationService locationService;

    @Resource
    private PolygonFenceService polygonFenceService;

    @Resource
    private VcomH5Service vcomH5Service;

    @Autowired
    private VcomPushUtils vcomPushUtils;

    @Autowired
    private VcomFenceService vcomFenceService;


    @Override
    public CommandRecordService getCommandRecordService() {
        return commandRecordService;
    }

    @Override
    public RedisService getRedis() {
        return redisService;
    }

    @Override
    public MqPhoneDatas getPhoneData(String imei, Integer deviceType, Integer customerId, String type, String commandNumber) {
        GetPhoneDatasEntity phoneDatas = getPhoneDatas(imei);
        if (phoneDatas != null) {
            MqPhoneDatas mqPhoneDatas = new MqPhoneDatas();
            mqPhoneDatas.setImei(imei);
            mqPhoneDatas.setType(type);
            mqPhoneDatas.setCommandNumber(commandNumber);
            List<PhoneData> phoneData = new ArrayList<>();
            List<VcomPhone> sosList = phoneDatas.getSos();
            List<VcomPhone> familyNoList = phoneDatas.getFamilyNoList();
            List<VcomPhone> whiteList = phoneDatas.getWhiteList();
            if (sosList != null && sosList.size() > 0) {
                for (VcomPhone vcomPhone : sosList) {
                    PhoneData phone = new PhoneData();
                    phone.setName(vcomPhone.getRelationship());
                    phone.setPhone(vcomPhone.getPhone());
                    phone.setPhoneType(String.valueOf(Constant.PHONE_SOS));
                    phone.setKey(vcomPhone.getPresskey());
                    phoneData.add(phone);
                }
            }
            if (familyNoList != null && familyNoList.size() > 0) {
                for (VcomPhone vcomPhone : familyNoList) {
                    PhoneData phone = new PhoneData();
                    phone.setName(vcomPhone.getRelationship());
                    phone.setPhone(vcomPhone.getPhone());
                    phone.setPhoneType(String.valueOf(Constant.PHONE_FAMILY));
                    Integer sequence = Integer.valueOf(vcomPhone.getPresskey()) + FAMILY_STEP_LENGTH;
                    phone.setKey(String.valueOf(sequence));
                    phoneData.add(phone);
                }
            }
            if (whiteList != null && whiteList.size() > 0) {
                for (int i = 1; i <= whiteList.size(); i++) {
                    VcomPhone vcomPhone = whiteList.get(i - 1);
                    PhoneData phone = new PhoneData();
                    phone.setName(vcomPhone.getRelationship());
                    phone.setPhone(vcomPhone.getPhone());
                    phone.setPhoneType(String.valueOf(Constant.PHONE_WHITE));
                    Integer sequence = i + WHITE_STEP_LENGTH;
                    phone.setKey(String.valueOf(sequence));
                    phoneData.add(phone);
                }
            }
            mqPhoneDatas.setPhoneDatas(phoneData);
            return mqPhoneDatas;
        }
        return null;
    }

    @Override
    public Boolean dealCustomerGetPhoneData(String imei, Integer deviceType, Integer customerId, String type, MqPhoneDatas phoneDatas) {
        if (CustomerDealCmdService.ALL_PHONE_TYPE.equals(type)) {
            deleteCacheCmd(imei, Constants.ALL_WHITELIST_NUMBER);
            deleteCacheCmd(imei, Constants.ALL_SOS_PHONE);
            //因为更新类型为所有号码类,故得重置所有号码类型为失败类型
            List<Integer> types = new ArrayList<>();//此处要求更新所有号码类型
            types.add(Constant.PHONE_SOS);
            types.add(Constant.PHONE_FAMILY);
            types.add(Constant.PHONE_WHITE);
            //发送中和未开始发送的重置掉
            List<Integer> states = new ArrayList<>();
            states.add(Constant.STATUS_NOT_SEND);
            states.add(Constant.STATUS_SEND);
            vcomPhoneService.updateVcomRequestStateByTypesAndImei(imei, types, states, Constant.STATUS_FAILED);
            vcomPhoneService.updatePhoneDateByImei(imei, type, phoneDatas);
            return true;
        }
        return false;
    }

    /**
     * 处理多边形围栏
     *
     * @param mqLocationData
     * @param deviceInfo
     * @param address
     * @param locationTime
     * @return
     */
    @Override
    public Boolean dealCustomerPolygonFence(MqLocationData mqLocationData, DeviceInfo deviceInfo, String address, long locationTime) {
        LocationData lastLocation = locationService.getLatestLocationData(deviceInfo.getDeviceId());
        if (lastLocation != null) {
            double lastLgn = Double.parseDouble(lastLocation.getLongitude());
            double lastLat = Double.parseDouble(lastLocation.getLatitude());
            //该设备号所绑定的vcom的,并且激活的多边形围栏
            List<PolygonFence> polygonFences = vcomFenceService.getPolygonFenceByImei(deviceInfo.getImei(),VcomFenceService.ACTIVE_FENCE);
            if (polygonFences != null && polygonFences.size() > 0) {
                for (PolygonFence polygonFence : polygonFences) {
                    //计算上一个点在围栏里面还是外面
                    String jsonPoints = polygonFence.getFencePoints();
                    List<FencePoints> fencePoints = JSONObject.parseArray(jsonPoints, FencePoints.class);
                    Double[] fenceLongitude = fencePoints.stream().map(FencePoints::getLongitude)
                            .collect(Collectors.toList()).toArray(new Double[fencePoints.size()]);
                    Double[] fenceLatitude = fencePoints.stream().map(FencePoints::getLatitude)
                            .collect(Collectors.toList()).toArray(new Double[fencePoints.size()]);
                    boolean lastLocationPoint = RegionUtil.isPolygonContainsPoint(fenceLongitude, fenceLatitude, fencePoints.size(), lastLgn, lastLat);
                    boolean currentPoint = RegionUtil.isPolygonContainsPoint(fenceLongitude, fenceLatitude, fencePoints.size(), mqLocationData.getLongitude(), mqLocationData.getLatitude());
                    Integer type = 0;
                    if (!lastLocationPoint && currentPoint) {//进围栏
                        if (polygonFence.getFenceType().equals(IN_FENCE) || polygonFence.getFenceType().equals(IN_AND_OUT_FENCE)) {
                            type = Constant.WARNING_PLAT_ENTER_FENCE;
                        }
                    } else if (lastLocationPoint && !currentPoint) {//出围栏
                        if (polygonFence.getFenceType().equals(OUT_FENCE) || polygonFence.getFenceType().equals(IN_AND_OUT_FENCE)) {
                            type = Constant.WARNING_PLAT_LEFT_FENCE;
                        }
                    }
                    if (type != 0) {
                        // 保存围栏告警通知
                        List<String> studentIds = vcomH5Service.getStudentIdByImei(deviceInfo.getImei());
                        if (studentIds != null && studentIds.size() > 0) {
                            for (String studentId : studentIds) {
                                VcomWarningRecord record = new VcomWarningRecord();
                                record.setTime(locationTime);
                                record.setType(type);
                                Map<String, Object> message = new HashMap<>();
                                message.put("fenceName", polygonFence.getFenceName());
                                message.put("address", address);
                                record.setMessage(JSONObject.toJSONString(message));
                                record.setImei(deviceInfo.getImei());
                                record.setStudentId("0");
                                if (!StringUtils.isBlank(studentId)) {
                                    record.setStudentId(studentId);
                                }
                                vcomH5Service.addVcomWarningRecord(record);
                            }
                        } else {
                            VcomWarningRecord record = new VcomWarningRecord();
                            record.setTime(locationTime);
                            record.setType(type);
                            Map<String, Object> message = new HashMap<>();
                            message.put("fenceName", polygonFence.getFenceName());
                            message.put("address", address);
                            record.setMessage(JSONObject.toJSONString(message));
                            record.setImei(deviceInfo.getImei());
                            record.setStudentId("0");
                            vcomH5Service.addVcomWarningRecord(record);
                        }
                        String info = "";
                        if (type == Constant.WARNING_PLAT_ENTER_FENCE) {
                            type=3;
                            info = "进入电子围栏:".concat(polygonFence.getFenceName());
                        } else if (type == Constant.WARNING_PLAT_LEFT_FENCE) {
                            type=4;
                            info = "出电子围栏:".concat(polygonFence.getFenceName());
                        }
                        vcomPushUtils.pushWarning(mqLocationData.getLatitude(), mqLocationData.getLongitude(),
                                address, type, info, locationTime, deviceInfo.getImei(), polygonFence.getFenceName(), polygonFence.getFenceId());
                    }
                }
            }
        }
        return false;
    }

    @Override
    public  GetPhoneDatasEntity getPhoneDatas(String imei) {
        try {
            logger.info("vcom send waterword url={}", URL.concat(GET_PHONE_URL.concat(imei)));
            String s = HttpclientUtil.get(URL.concat(GET_PHONE_URL.concat(imei)),null,"UTF-8");
            logger.info("vcom reply waterword param={}", s);
            VcomData vcomData = JSONObject.parseObject(s, VcomData.class);
            if (vcomData.getCode().equals(SUCCESS_CODE)) {
               return JSONObject.parseObject(vcomData.getData().toString(),GetPhoneDatasEntity.class);
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {

        VcomServiceImpl vcomService = new VcomServiceImpl();
        GetPhoneDatasEntity phoneDatas = vcomService.getPhoneDatas("866248053272207");
        System.out.println(phoneDatas);
    }
}
